/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import DAO.ImageDAO;
import DAO.PropertyDAO;
import Model.FarmBean;
import Model.ImageBean;
import Model.PropertyBean;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletContext;

import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author amkreuz
 */
@Named(value = "propertyController")
@SessionScoped
public class PropertyController implements Serializable {

    private PropertyBean bean;
    private boolean sendEmail = false;

    public boolean isSendEmail() {
        return sendEmail;
    }

    public void setSendEmail(boolean sendEmail) {
        this.sendEmail = sendEmail;
    }

    public PropertyController() {
        bean = new PropertyBean();
    }

    public PropertyBean getBean() {
        return bean;
    }

    public void setBean(PropertyBean bean) {
        this.bean = bean;
    }

    public String uploadProperty() {
        try {
            PropertyDAO.init();

            FarmBean userbean = (FarmBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");

            PropertyDAO.createProperty(bean);
            PropertyDAO.terminate();
            FacesContext facesContext = FacesContext.getCurrentInstance();
            FacesMessage facesMessage = new FacesMessage("Property Created Successfully");
            facesContext.addMessage(null, facesMessage);

            return "UploadImage.xhtml";
        } catch (SQLException ex) {
            Logger.getLogger(PropertyController.class.getName()).log(Level.SEVERE, null, ex);
            try {
                PropertyDAO.terminate();
            } catch (SQLException ex1) {
                Logger.getLogger(PropertyController.class.getName()).log(Level.SEVERE, null, ex1);
            }
            FacesContext facesContext = FacesContext.getCurrentInstance();
            FacesMessage facesMessage = new FacesMessage("Error Creating Property");
            facesContext.addMessage(null, facesMessage);
            return "";
        }
    }

    public void upload(FileUploadEvent event) {
        try {
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void copyFile(String fileName, InputStream in) {
        try {

            String relativeWebPath = "\\resources\\images";

            ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
            String absoluteDiskPath = servletContext.getRealPath(relativeWebPath);
            String toWrite;

            String PropertyID = bean.getAddress().replaceAll("\\s", "") + "-" + bean.getZip();

            absoluteDiskPath += "\\" + PropertyID;
            if (Files.notExists(FileSystems.getDefault().getPath(absoluteDiskPath))) {
                File dir = new File(absoluteDiskPath);
                dir.mkdir();
            }
            toWrite = absoluteDiskPath;
            absoluteDiskPath += "\\" + fileName;

            File file = new File(absoluteDiskPath);
            OutputStream out = null;
            try {
                PropertyDAO.init();
                int images = PropertyDAO.getImages(bean) + 1;
                toWrite += "\\" + images;
                PropertyDAO.updateImagePath(bean, toWrite);
                PropertyDAO.terminate();
                out = new FileOutputStream(toWrite);
                FacesContext facesContext = FacesContext.getCurrentInstance();
                FacesMessage facesMessage = new FacesMessage("Image Uploaded");
                facesContext.addMessage(null, facesMessage);
            } catch (SQLException ex) {
                Logger.getLogger(PropertyController.class.getName()).log(Level.SEVERE, null, ex);
            }
            // write the inputStream to a FileOutputStream
            //           OutputStream out = new FileOutputStream(toWrite);

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            in.close();
            out.flush();
            out.close();

            System.out.println("New file created at:" + file.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }

    public ArrayList<ImageBean> getImages() {

        ArrayList<ImageBean> list = null;
        try {
            ImageDAO.init();
            list = ImageDAO.getImageList(bean);
            ImageDAO.terminate();
        } catch (SQLException ex) {
            Logger.getLogger(ImageBean.class.getName()).log(Level.SEVERE, null, ex);
        }

        return list;
    }
    /*
     public ArrayList<PropertyBean> getAllProperties() throws SQLException {
     PropertyDAO propDAO = new PropertyDAO();
     ArrayList<PropertyBean> allProperties = propDAO.returnProperties();
     for (int i = 0; i < allProperties.size(); i++)
     {
     String propID = allProperties.get(i).getAddress() + "-" + allProperties.get(i).getZip();
     FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(propID,allProperties.get(i));
     }
     return allProperties;
     }
     */
    
       public ArrayList<ImageBean> getImages(PropertyBean bean) {

        ArrayList<ImageBean> list = null;
        
        try {
            ImageDAO.init();
            list = ImageDAO.getImageList(bean);
            ImageDAO.terminate();
        } catch (SQLException ex) {
            Logger.getLogger(ImageBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return list;
    }
}
